"""
态势对象数据同步 API 路由
"""
from typing import List, Optional
from uuid import UUID
from datetime import datetime
import uuid as uuid_lib
from fastapi import APIRouter, Depends, HTTPException, Query, Body
from sqlalchemy.ext.asyncio import AsyncSession

from src.situation.database import get_db
from src.situation.sync_service import DataSyncService
from src.situation.sync_schemas import (
    DataSourceCreate, DataSourceUpdate, DataSourceResponse, DataSourceListResponse,
    SyncTaskCreate, SyncTaskUpdate, SyncTaskResponse, SyncTaskWithMappingsResponse,
    SyncTaskListResponse, SyncLogResponse, SyncLogListResponse,
    TestConnectionResponse, TableStructureResponse, SyncExecutionResponse,
    SyncStatisticsResponse, DatabaseType, SyncStatus, SyncMode, ExecutionStatus,
    SyncTaskFilter, BatchSyncRequest, BatchSyncResponse
)
from server.utils.auth_middleware import get_admin_user, get_required_user
from server.models.user_model import User
from src.utils import logger

sync_router = APIRouter(prefix="/situation", tags=["situation-sync"])


# ============================================================================
# === 数据源管理 API ===
# ============================================================================

@sync_router.post("/data-sources", response_model=DataSourceResponse)
async def create_data_source(
    data_source: DataSourceCreate,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_admin_user)
):
    """创建数据源"""
    logger.info(f"[同步API] 创建数据源请求: {data_source.name}")

    try:
        result = await DataSyncService.create_data_source(db, data_source, current_user.username if current_user else None)
        logger.info(f"[同步API] 数据源创建成功: {result.id}")
        return result
    except ValueError as ve:
        logger.warning(f"[同步API] 创建数据源业务逻辑错误: {ve}")
        raise HTTPException(status_code=400, detail=str(ve))
    except Exception as e:
        logger.error(f"[同步API] 创建数据源系统错误: {type(e).__name__}: {e}")
        raise HTTPException(status_code=500, detail="创建数据源失败")


@sync_router.get("/data-sources", response_model=DataSourceListResponse)
async def get_data_sources(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页大小"),
    db_type: Optional[DatabaseType] = Query(None, description="数据库类型"),
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_required_user)
):
    """获取数据源列表"""
    try:
        data_sources, total = await DataSyncService.get_data_sources(
            db, page=page, page_size=page_size, db_type=db_type
        )
        return DataSourceListResponse(
            items=data_sources,
            total=total,
            page=page,
            page_size=page_size
        )
    except Exception as e:
        logger.error(f"[同步API] 获取数据源列表失败: {e}")
        raise HTTPException(status_code=500, detail="获取数据源列表失败")


@sync_router.get("/data-sources/{source_id}", response_model=DataSourceResponse)
async def get_data_source(
    source_id: UUID,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_required_user)
):
    """获取数据源详情"""
    try:
        data_source = await DataSyncService.get_data_source_by_id(db, source_id)
        if not data_source:
            raise HTTPException(status_code=404, detail="数据源不存在")
        return data_source
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"[同步API] 获取数据源详情失败: {e}")
        raise HTTPException(status_code=500, detail="获取数据源详情失败")


@sync_router.put("/data-sources/{source_id}", response_model=DataSourceResponse)
async def update_data_source(
    source_id: UUID,
    data_source: DataSourceUpdate,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_admin_user)
):
    """更新数据源"""
    try:
        result = await DataSyncService.update_data_source(
            db, source_id, data_source, current_user.username if current_user else None
        )
        return result
    except ValueError as ve:
        raise HTTPException(status_code=400, detail=str(ve))
    except Exception as e:
        logger.error(f"[同步API] 更新数据源失败: {e}")
        raise HTTPException(status_code=500, detail="更新数据源失败")


@sync_router.delete("/data-sources/{source_id}")
async def delete_data_source(
    source_id: UUID,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_admin_user)
):
    """删除数据源"""
    try:
        success = await DataSyncService.delete_data_source(db, source_id)
        return {"success": success, "message": "数据源删除成功"}
    except ValueError as ve:
        raise HTTPException(status_code=400, detail=str(ve))
    except Exception as e:
        logger.error(f"[同步API] 删除数据源失败: {e}")
        raise HTTPException(status_code=500, detail="删除数据源失败")


@sync_router.post("/data-sources/{source_id}/test-connection", response_model=TestConnectionResponse)
async def test_data_source_connection(
    source_id: UUID,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_admin_user)
):
    """测试数据源连接"""
    try:
        result = await DataSyncService.test_connection(db, source_id)
        return result
    except ValueError as ve:
        raise HTTPException(status_code=400, detail=str(ve))
    except Exception as e:
        logger.error(f"[同步API] 测试数据源连接失败: {e}")
        raise HTTPException(status_code=500, detail="测试数据源连接失败")


@sync_router.get("/data-sources/{source_id}/tables/{table_name}/structure", response_model=TableStructureResponse)
async def get_table_structure(
    source_id: UUID,
    table_name: str,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_admin_user)
):
    """获取表结构"""
    try:
        result = await DataSyncService.get_table_structure(db, source_id, table_name)
        return result
    except ValueError as ve:
        raise HTTPException(status_code=400, detail=str(ve))
    except Exception as e:
        logger.error(f"[同步API] 获取表结构失败: {e}")
        raise HTTPException(status_code=500, detail="获取表结构失败")


# ============================================================================
# === 同步任务管理 API ===
# ============================================================================

@sync_router.post("/sync-tasks", response_model=SyncTaskWithMappingsResponse)
async def create_sync_task(
    sync_task: SyncTaskCreate,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_admin_user)
):
    """创建同步任务"""
    logger.info(f"[同步API] 创建同步任务请求: {sync_task.task_name}")

    try:
        result = await DataSyncService.create_sync_task(db, sync_task, current_user.username if current_user else None)

        # 重新获取包含字段映射的任务信息
        result_with_mappings = await DataSyncService.get_sync_task_by_id(db, result.id)

        logger.info(f"[同步API] 同步任务创建成功: {result.id}")
        return result_with_mappings
    except ValueError as ve:
        logger.warning(f"[同步API] 创建同步任务业务逻辑错误: {ve}")
        raise HTTPException(status_code=400, detail=str(ve))
    except Exception as e:
        logger.error(f"[同步API] 创建同步任务系统错误: {type(e).__name__}: {e}")
        raise HTTPException(status_code=500, detail="创建同步任务失败")


@sync_router.get("/sync-tasks", response_model=SyncTaskListResponse)
async def get_sync_tasks(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页大小"),
    task_name: Optional[str] = Query(None, description="任务名称"),
    sync_status: Optional[SyncStatus] = Query(None, description="同步状态"),
    sync_mode: Optional[SyncMode] = Query(None, description="同步模式"),
    data_source_id: Optional[UUID] = Query(None, description="数据源ID"),
    is_active: Optional[bool] = Query(None, description="是否启用"),
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_required_user)
):
    """获取同步任务列表"""
    try:
        filters = {}
        if task_name:
            filters['task_name'] = task_name
        if sync_status:
            filters['sync_status'] = sync_status
        if sync_mode:
            filters['sync_mode'] = sync_mode
        if data_source_id:
            filters['data_source_id'] = data_source_id
        if is_active is not None:
            filters['is_active'] = is_active

        sync_tasks, total = await DataSyncService.get_sync_tasks(
            db, page=page, page_size=page_size, filters=filters
        )
        return SyncTaskListResponse(
            items=sync_tasks,
            total=total,
            page=page,
            page_size=page_size
        )
    except Exception as e:
        logger.error(f"[同步API] 获取同步任务列表失败: {e}")
        raise HTTPException(status_code=500, detail="获取同步任务列表失败")


@sync_router.get("/sync-tasks/{task_id}", response_model=SyncTaskWithMappingsResponse)
async def get_sync_task(
    task_id: UUID,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_required_user)
):
    """获取同步任务详情"""
    try:
        sync_task = await DataSyncService.get_sync_task_by_id(db, task_id)
        if not sync_task:
            raise HTTPException(status_code=404, detail="同步任务不存在")
        return sync_task
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"[同步API] 获取同步任务详情失败: {e}")
        raise HTTPException(status_code=500, detail="获取同步任务详情失败")


@sync_router.put("/sync-tasks/{task_id}", response_model=SyncTaskResponse)
async def update_sync_task(
    task_id: UUID,
    sync_task: SyncTaskUpdate,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_admin_user)
):
    """更新同步任务"""
    try:
        # 获取现有任务
        existing_task = await DataSyncService.get_sync_task_by_id(db, task_id)
        if not existing_task:
            raise HTTPException(status_code=404, detail="同步任务不存在")

        # 这里可以添加更新逻辑，暂时返回现有任务
        # TODO: 实现完整的更新逻辑
        logger.info(f"[同步API] 更新同步任务功能待完全实现: {task_id}")
        return existing_task
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"[同步API] 更新同步任务失败: {e}")
        raise HTTPException(status_code=500, detail="更新同步任务失败")


@sync_router.delete("/sync-tasks/{task_id}")
async def delete_sync_task(
    task_id: UUID,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_admin_user)
):
    """删除同步任务"""
    try:
        # 检查任务是否存在
        existing_task = await DataSyncService.get_sync_task_by_id(db, task_id)
        if not existing_task:
            raise HTTPException(status_code=404, detail="同步任务不存在")

        # TODO: 实现软删除逻辑
        logger.info(f"[同步API] 删除同步任务功能待完全实现: {task_id}")
        return {"success": True, "message": "同步任务删除成功（功能待完全实现）"}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"[同步API] 删除同步任务失败: {e}")
        raise HTTPException(status_code=500, detail="删除同步任务失败")


@sync_router.post("/sync-tasks/{task_id}/activate")
async def activate_sync_task(
    task_id: UUID,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_admin_user)
):
    """启用同步任务"""
    try:
        existing_task = await DataSyncService.get_sync_task_by_id(db, task_id)
        if not existing_task:
            raise HTTPException(status_code=404, detail="同步任务不存在")

        # TODO: 实现启用逻辑
        logger.info(f"[同步API] 启用同步任务功能待完全实现: {task_id}")
        return {"success": True, "message": "同步任务启用成功（功能待完全实现）"}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"[同步API] 启用同步任务失败: {e}")
        raise HTTPException(status_code=500, detail="启用同步任务失败")


@sync_router.post("/sync-tasks/{task_id}/deactivate")
async def deactivate_sync_task(
    task_id: UUID,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_admin_user)
):
    """禁用同步任务"""
    try:
        existing_task = await DataSyncService.get_sync_task_by_id(db, task_id)
        if not existing_task:
            raise HTTPException(status_code=404, detail="同步任务不存在")

        # TODO: 实现禁用逻辑
        logger.info(f"[同步API] 禁用同步任务功能待完全实现: {task_id}")
        return {"success": True, "message": "同步任务禁用成功（功能待完全实现）"}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"[同步API] 禁用同步任务失败: {e}")
        raise HTTPException(status_code=500, detail="禁用同步任务失败")


# ============================================================================
# === 同步执行 API ===
# ============================================================================

@sync_router.post("/sync-tasks/{task_id}/execute", response_model=SyncExecutionResponse)
async def execute_sync_task(
    task_id: UUID,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_admin_user)
):
    """立即执行同步任务"""
    try:
        result = await DataSyncService.execute_sync_task(db, task_id, current_user.username if current_user else None)
        return result
    except ValueError as ve:
        raise HTTPException(status_code=400, detail=str(ve))
    except Exception as e:
        logger.error(f"[同步API] 执行同步任务失败: {e}")
        raise HTTPException(status_code=500, detail="执行同步任务失败")


@sync_router.post("/sync-execution/batch", response_model=BatchSyncResponse)
async def batch_execute_sync_tasks(
    request: BatchSyncRequest,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_admin_user)
):
    """批量执行同步任务"""
    try:
        # TODO: 实现真正的批量执行逻辑
        results = []
        successful_tasks = 0
        failed_tasks = 0

        for task_id in request.task_ids:
            try:
                # 检查任务是否存在
                task = await DataSyncService.get_sync_task_by_id(db, task_id)
                if task:
                    # 暂时只是模拟执行
                    results.append({
                        "task_id": task_id,
                        "execution_id": f"exec_batch_{uuid_lib.uuid4().hex[:8]}",
                        "success": True,
                        "message": "批量执行启动成功（功能待完全实现）"
                    })
                    successful_tasks += 1
                else:
                    results.append({
                        "task_id": task_id,
                        "success": False,
                        "message": "任务不存在"
                    })
                    failed_tasks += 1
            except Exception as e:
                results.append({
                    "task_id": task_id,
                    "success": False,
                    "message": f"执行失败: {str(e)}"
                })
                failed_tasks += 1

        logger.info(f"[同步API] 批量执行完成: 成功 {successful_tasks}, 失败 {failed_tasks}")

        return BatchSyncResponse(
            total_tasks=len(request.task_ids),
            successful_tasks=successful_tasks,
            failed_tasks=failed_tasks,
            results=results
        )
    except Exception as e:
        logger.error(f"[同步API] 批量执行同步任务失败: {e}")
        raise HTTPException(status_code=500, detail="批量执行同步任务失败")


@sync_router.post("/sync-execution/{execution_id}/stop")
async def stop_sync_execution(
    execution_id: str,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_admin_user)
):
    """停止同步执行"""
    try:
        # TODO: 实现真正的停止执行逻辑
        logger.info(f"[同步API] 停止同步执行功能待完全实现: {execution_id}")
        return {"success": True, "message": "同步执行停止成功（功能待完全实现）"}
    except Exception as e:
        logger.error(f"[同步API] 停止同步执行失败: {e}")
        raise HTTPException(status_code=500, detail="停止同步执行失败")


# ============================================================================
# === 同步日志 API ===
# ============================================================================

@sync_router.get("/sync-logs", response_model=SyncLogListResponse)
async def get_sync_logs(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页大小"),
    task_id: Optional[UUID] = Query(None, description="同步任务ID"),
    status: Optional[ExecutionStatus] = Query(None, description="执行状态"),
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_required_user)
):
    """获取同步日志列表"""
    try:
        # TODO: 实现真正的日志查询逻辑
        # 暂时返回空列表
        logger.info(f"[同步API] 获取同步日志列表功能待完全实现")
        return SyncLogListResponse(
            items=[],
            total=0,
            page=page,
            page_size=page_size
        )
    except Exception as e:
        logger.error(f"[同步API] 获取同步日志列表失败: {e}")
        raise HTTPException(status_code=500, detail="获取同步日志列表失败")


@sync_router.get("/sync-logs/{log_id}", response_model=SyncLogResponse)
async def get_sync_log(
    log_id: UUID,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_required_user)
):
    """获取同步日志详情"""
    try:
        # TODO: 实现真正的日志详情查询逻辑
        logger.info(f"[同步API] 获取同步日志详情功能待完全实现: {log_id}")
        raise HTTPException(status_code=404, detail="同步日志不存在（功能待完全实现）")
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"[同步API] 获取同步日志详情失败: {e}")
        raise HTTPException(status_code=500, detail="获取同步日志详情失败")


# ============================================================================
# === 统计信息 API ===
# ============================================================================

@sync_router.get("/sync-statistics", response_model=SyncStatisticsResponse)
async def get_sync_statistics(
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_required_user)
):
    """获取同步统计信息"""
    try:
        result = await DataSyncService.get_sync_statistics(db)
        return result
    except Exception as e:
        logger.error(f"[同步API] 获取同步统计信息失败: {e}")
        raise HTTPException(status_code=500, detail="获取同步统计信息失败")